package com.qk.utils;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import com.aliyuncs.exceptions.ClientException;
import com.qk.config.AliYunOSSProperties;
import com.qk.enums.ParamEnum;
import com.qk.exception.CommonException;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author lyl
 * @created 2025/10/6 16:18
 * @description
 *
 */



@Slf4j
@Component
@SuppressWarnings("all")
public class AliYunOSSOperators {

    @Autowired
    private AliYunOSSProperties aliyunOSSProperties;

    private  String endpoint;
    private  String bucketName;
    private  String region;
    private  ClientBuilderConfiguration clientBuilderConfiguration;

    @PostConstruct
    public void init() {
        this.endpoint = aliyunOSSProperties.getEndpoint();
        this.bucketName = aliyunOSSProperties.getBucketName();
        this.region = aliyunOSSProperties.getRegion();
        this.clientBuilderConfiguration = new ClientBuilderConfiguration();
    }

    private OSS createOSSClient() {
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        return OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
    }
    public String upload(byte[] content, String objectName) throws Exception {

        // 创建OSSClient实例
        OSS ossClient = null;
        try {
            ossClient = createOSSClient();
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));
            // 上传文件
            ossClient.putObject(putObjectRequest);
            // 返回文件访问URL
            return "https://" + bucketName + "." + endpoint.substring(8) + "/" + objectName;
        } catch (Exception e) {
            log.error("Caught an OSSException: " + e.getMessage());
            throw e;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    public void deleteFiles(List<String> fileNames) throws Exception {

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        OSS ossClient = null;
        try {
            ossClient = createOSSClient();
            // 删除文件。
            // 填写需要删除的多个文件完整路径。文件完整路径中不能包含Bucket名称。
            List<String> keys = new ArrayList<>();
            if (CollectionUtils.isEmpty(fileNames)){
                CommonException.throwCommonException(ParamEnum.PARAM_NOT_EXIST);
            }
            // 获取所有文件列表
            List<String> allFiles = getAllFiles();

            // 过滤出不在fileNames中的文件
            for (String file : allFiles) {
                log.info("OSS获取到的fileName:{}",file);
                if (!fileNames.contains(file)) {
                    log.info("定时删除任务执行完成，准备删除的文件{}", file);
                    keys.add(file);
                }
            }
            log.info("定时删除任务执行完成，共删除 {} 个文件", keys.size());

            ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url"));

        } catch (Exception oe) {
            log.error("在排列删除文件：Caught an OSSException: {}", oe.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    public List<String> getAllFiles() throws ClientException {

        List<String> fileKeys = new ArrayList<>();
        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        OSS ossClient = null;
        try {
            ossClient = createOSSClient();
            // 构造ListObjectsRequest请求。
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

            // 列举文件。
            ObjectListing listing = ossClient.listObjects(listObjectsRequest);

            // 遍历所有文件。
            for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                fileKeys.add(objectSummary.getKey());
            }
            return fileKeys;

        } catch (Exception oe) {
            log.error("在获取所有文件：Caught an OSSException: {}", oe.getMessage());
            return fileKeys;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
